﻿namespace Loki.Client
{
    public static class LokiExtensions
    {
        private const long NanosecondsPerTick = 100;
        private static readonly DateTimeOffset UnixEpoch = new(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);

        public static string ToUnixNanosecondsString(this DateTimeOffset offset) =>
            ((offset - UnixEpoch).Ticks * NanosecondsPerTick).ToString();

        public static LokiException ToLokiException(this Exception ex)
        {
            if (ex == null)
            {
                return null;
            }

            var typeNamespace = ex.GetType().Namespace;
            var typeName = typeNamespace != null && typeNamespace.StartsWith("System.") ? ex.GetType().Name : ex.GetType().ToString();

            var lokiEx = new LokiException
            {
                Type = typeName,
                Message = ex.Message ?? "",
                StackTrace = ex.StackTrace ?? ""
            };

            if (ex.InnerException != null)
            {
                var typeNamespace2 = ex.InnerException.GetType().Namespace;
                var typeName2 = typeNamespace2 != null && typeNamespace2.StartsWith("System.") ? ex.InnerException.GetType().Name : ex.InnerException.GetType().ToString();
                lokiEx.InnerException = new LokiInnerException
                {
                    Type = typeName2,
                    Message = ex.InnerException.Message ?? "",
                    StackTrace = ex.InnerException.StackTrace ?? ""
                };
            }

            return lokiEx;
        }
    }
}
